Algorithms for calculating covariance